Introduction to Open Data Science - Course Project

About the project

This is a course diary for the UH course Introduction to Open Data Science. I was introduced to this course by our PhD-program’s advisor and it will be included as a course in my transferrable studies quota (10 credits).

The link for this diary is: https://villetan.github.io/IODS-project/

# This is a so-called "R chunk" where you can write R code.

date()
## [1] "Fri Nov 26 20:32:46 2021"

Linear Regression

Describe the work you have done this week and summarize your learning.

setwd("~/Koulu/IODS-project")
date()
## [1] "Fri Nov 26 20:32:46 2021"

Lets read the data in from local file…

data = read.csv("data/wk2data.csv")

… and see the summary of it.

summary(data)
##     gender               Age           Attitude         Points     
##  Length:166         Min.   :17.00   Min.   :14.00   Min.   : 7.00  
##  Class :character   1st Qu.:21.00   1st Qu.:26.00   1st Qu.:19.00  
##  Mode  :character   Median :22.00   Median :32.00   Median :23.00  
##                     Mean   :25.51   Mean   :31.43   Mean   :22.72  
##                     3rd Qu.:27.00   3rd Qu.:37.00   3rd Qu.:27.75  
##                     Max.   :55.00   Max.   :50.00   Max.   :33.00  
##       deep            stra            surf      
##  Min.   :1.583   Min.   :1.250   Min.   :1.583  
##  1st Qu.:3.333   1st Qu.:2.625   1st Qu.:2.417  
##  Median :3.667   Median :3.188   Median :2.833  
##  Mean   :3.680   Mean   :3.121   Mean   :2.787  
##  3rd Qu.:4.083   3rd Qu.:3.625   3rd Qu.:3.167  
##  Max.   :4.917   Max.   :5.000   Max.   :4.333

Let’s also plot a graphical summary.

library(GGally)
## Loading required package: ggplot2
## Registered S3 method overwritten by 'GGally':
##   method from   
##   +.gg   ggplot2
library(ggplot2)
p <- ggpairs(data, mapping = aes(), lower = list(combo = wrap("facethist", bins = 20)))
p

First, lets look at the distributions of the variables individually. There are more females present in the data set. The ages of the subjects are right skewed, so that people in their 20’s are more prevalent. Points have a small spike in presence of low points, but other than that it is near Gaussian in the region above 15 points. Other variables seem to be balanced rather well over their domain.

To name few interesting or meaningful pairwise relationships, the correlation between deep and surf variables is the highest. Without knowing too much about them, they sound likethey should indeed have negative correlation: High deep approach to the course, would mean low surface approach to the course. Another clear correlation is between Attitude and Points: good attitude correlates with good score from the course. We should be careful of commenting on causal relationship, but for the layman this would suggest that good attitudes yield good scores.

Next, lets fit a regression model with three variables and print the summary.

lm_fit = lm("Points ~ Attitude + deep + stra", data = data)
summary(lm_fit)
## 
## Call:
## lm(formula = "Points ~ Attitude + deep + stra", data = data)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -17.5239  -3.4276   0.5474   3.8220  11.5112 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 11.39145    3.40775   3.343  0.00103 ** 
## Attitude     0.35254    0.05683   6.203 4.44e-09 ***
## deep        -0.74920    0.75066  -0.998  0.31974    
## stra         0.96208    0.53668   1.793  0.07489 .  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 5.289 on 162 degrees of freedom
## Multiple R-squared:  0.2097, Adjusted R-squared:  0.195 
## F-statistic: 14.33 on 3 and 162 DF,  p-value: 2.521e-08

It seems that the attitude is the only statistically significant feature explaining good (or bad) points in the course. What this means in laymen terms is that the coefficients for the deep and stra might as well have been 0 and thus they would have not contributed to the score itself.

Lets remove stra and deep since they are non-significant, we’ll also keep the Intercept therm as it showed significance as well.

lm_fit_ = lm("Points ~ Attitude", data = data)
summary(lm_fit_)
## 
## Call:
## lm(formula = "Points ~ Attitude", data = data)
## 
## Residuals:
##      Min       1Q   Median       3Q      Max 
## -16.9763  -3.2119   0.4339   4.1534  10.6645 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 11.63715    1.83035   6.358 1.95e-09 ***
## Attitude     0.35255    0.05674   6.214 4.12e-09 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 5.32 on 164 degrees of freedom
## Multiple R-squared:  0.1906, Adjusted R-squared:  0.1856 
## F-statistic: 38.61 on 1 and 164 DF,  p-value: 4.119e-09

Now, they both are significant with p-values effectively zero. This means that we can be pretty certain that the coefficient estimates are not zeros.

The relationship between Attitude and Points is clear positive trend as seen on the plot below. There the regression line found is plotted with black solid line.

plot(data$Attitude, data$Points, xlab = "Attitide", ylab="Points")
abline(a=lm_fit_$coefficients["(Intercept)"], b=lm_fit_$coefficients["Attitude"])

The multiple R-squared is the proportion of variance explained by the linear model. So the linear model explains about 20% of the variance in the response variable, that is, points. The rest of the 80% of the variance seem to be inherent to the data.

Lets plot Residuals vs. fitted values, normal QQ-plot and residual vs. leverage.

par(mfrow=c(2,2))
plot(lm_fit_, which = c(1,2,5))

The interpretation of “Residuals vs. fitted” is that one can see where the linear model makes mistakes. For example if there is non-linearity, then it is expected to be visible in this plot. The closer to the zero line the residuals are, the better the model. A perfect model would have a straight line at 0. In our model there is no pattern of nonlinearity as the points are uniformly distributed across different locations of x-axis.

The second plot, the QQ-plot, estimates if the errors of the model are really normally distributed, which is an assumption of the linear model. Since the QQ-plot is not completely straight, there are slight evidence, that the residuals are not Normal, but rather left skewed. See the plot below. However, the skew is very minor.

The third plot, Residuals vs. leverage, studies if a single (or a group) data point is responsible for the “fit” more than the others. It seems that no single data point is affecting the fit significantly more than others.

hist(lm_fit_$residuals, main="Residuals")

Logistic Regression

Lets read the data we generated using create_alc.R script and see that it looks ok.

alc_data = read.csv("data/alc_data.csv")
print(dim(alc_data))
## [1] 370  35
str(alc_data)
## 'data.frame':    370 obs. of  35 variables:
##  $ school    : chr  "GP" "GP" "GP" "GP" ...
##  $ sex       : chr  "F" "F" "F" "F" ...
##  $ age       : int  15 15 15 15 15 15 15 15 15 15 ...
##  $ address   : chr  "R" "R" "R" "R" ...
##  $ famsize   : chr  "GT3" "GT3" "GT3" "GT3" ...
##  $ Pstatus   : chr  "T" "T" "T" "T" ...
##  $ Medu      : int  1 1 2 2 3 3 3 2 3 3 ...
##  $ Fedu      : int  1 1 2 4 3 4 4 2 1 3 ...
##  $ Mjob      : chr  "at_home" "other" "at_home" "services" ...
##  $ Fjob      : chr  "other" "other" "other" "health" ...
##  $ reason    : chr  "home" "reputation" "reputation" "course" ...
##  $ guardian  : chr  "mother" "mother" "mother" "mother" ...
##  $ traveltime: int  2 1 1 1 2 1 2 2 2 1 ...
##  $ studytime : int  4 2 1 3 3 3 3 2 4 4 ...
##  $ schoolsup : chr  "yes" "yes" "yes" "yes" ...
##  $ famsup    : chr  "yes" "yes" "yes" "yes" ...
##  $ activities: chr  "yes" "no" "yes" "yes" ...
##  $ nursery   : chr  "yes" "no" "yes" "yes" ...
##  $ higher    : chr  "yes" "yes" "yes" "yes" ...
##  $ internet  : chr  "yes" "yes" "no" "yes" ...
##  $ romantic  : chr  "no" "yes" "no" "no" ...
##  $ famrel    : int  3 3 4 4 4 4 4 4 4 4 ...
##  $ freetime  : int  1 3 3 3 2 3 2 1 4 3 ...
##  $ goout     : int  2 4 1 2 1 2 2 3 2 3 ...
##  $ Dalc      : int  1 2 1 1 2 1 2 1 2 1 ...
##  $ Walc      : int  1 4 1 1 3 1 2 3 3 1 ...
##  $ health    : int  1 5 2 5 3 5 5 4 3 4 ...
##  $ alc_use   : num  1 3 1 1 2.5 1 2 2 2.5 1 ...
##  $ high_use  : logi  FALSE TRUE FALSE FALSE TRUE FALSE ...
##  $ failures  : int  0 1 0 0 1 0 1 0 0 0 ...
##  $ paid      : chr  "yes" "no" "no" "no" ...
##  $ absences  : int  3 2 8 2 5 2 0 1 9 10 ...
##  $ G1        : int  10 10 14 10 12 12 11 10 16 10 ...
##  $ G2        : int  12 8 13 10 12 12 6 10 16 10 ...
##  $ G3        : int  12 8 12 9 12 12 6 10 16 10 ...

Let us select 4 interesting variables to seek the relationship with the alcohol consumption.

interesting_cols = c("freetime", "romantic", "address", "famrel")

The hypothesis is that these variables correlate with alieness to the society, which in turn, I speculate, affects the alcohol consumption. I speculate that freetime and ruralness correlate with alcohol consumption positively, while being in a romantic relationship and having good family relations correlate negatively.

library(ggplot2)
library(GGally)
cor_data = alc_data[, c("alc_use", interesting_cols)]
#cast as factors so that they are visualised correctly
cor_data$freetime = as.factor(cor_data$freetime)
cor_data$romantic = as.factor(cor_data$romantic)
cor_data$address = as.factor(cor_data$address)
cor_data$famrel = as.factor(cor_data$famrel)
ggpairs(cor_data)
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

I have non-significant support for the hypotheses made above for all but “romantic” relationship. So it seems that relationship status has absolutely no correlation with the alcohol consumption.

Lets study the problem with logistic regression model.

cor_data$freetime = as.numeric(cor_data$freetime)
cor_data$famrel = as.numeric(cor_data$famrel)
glm_data = cbind("high_use"=alc_data$high_use, cor_data[,interesting_cols])
logreg_fit = glm(high_use ~ ., data = glm_data, family="binomial")

For the continuous (ordinal features, that is, freetime and famrel) we can exponentiate, to get the odds ratios:

exp(logreg_fit$coefficients[c("freetime", "famrel")])
##  freetime    famrel 
## 1.5537064 0.6932053

So free time, being having a unit more of free time, increases the chances of high use of alcohol 1.5 times higher. On the other hand, having a unit increase in family relations, that is having better family relationships, makes decreases the chances of high use of alcohol by 1.45 times (because 0.69, which is 1 / 1.45).

The same happens with the discrete features, but we need to be careful with the interpretation of unit addition.

exp(logreg_fit$coefficients[c("romanticyes", "addressU")])
## romanticyes    addressU 
##   0.7760629   0.5883402

Here it seems that romantic relation and address in urban area seem to have negative effect on the high use of alcohol, just like predicted.

The confidence intervals can be fetched with the following command

exp(confint(logreg_fit))
## Waiting for profiling to be done...
##                 2.5 %    97.5 %
## (Intercept) 0.1940075 2.3182620
## freetime    1.2228777 1.9926747
## romanticyes 0.4657483 1.2726638
## addressU    0.3451026 1.0102441
## famrel      0.5378060 0.8906739

So, the only confidence intervals not covering the “no effect” value of 1 are freetime and famrel, meaning that they provide more statistical evidence that indeed more freetime is associated with higher use and better family relationships are related with not high use.

Lets create the 2x2 cross-tabulation, also known as confusion matrix,

cmat = table(high_use = glm_data$high_use, prediction = (predict(logreg_fit, newdata=glm_data, type="response") > 0.5))
print(cmat)
##         prediction
## high_use FALSE TRUE
##    FALSE   248   11
##    TRUE    104    7

and compute the training error:

#training error:
sum(c(cmat[1,2], cmat[2,1])) / sum(cmat)
## [1] 0.3108108
#random guessing:
print(mean(glm_data$high_use))
## [1] 0.3

The model misclassifices 31% of the training cases. So the interpretation is that on average 3 out of 10 samples is misclassified. With random guessing one gets, on average, as low errors as predicting the majority class. That is, the random guessing is actually better, because it gets an error as low as 30%. So this means that the model fit to the data is actually very poor, and the interpretation should not be trusted.

Clustering and Classification

Let us look at the Boston dataset from MASS package

library(MASS)
data = Boston
str(data)
## 'data.frame':    506 obs. of  14 variables:
##  $ crim   : num  0.00632 0.02731 0.02729 0.03237 0.06905 ...
##  $ zn     : num  18 0 0 0 0 0 12.5 12.5 12.5 12.5 ...
##  $ indus  : num  2.31 7.07 7.07 2.18 2.18 2.18 7.87 7.87 7.87 7.87 ...
##  $ chas   : int  0 0 0 0 0 0 0 0 0 0 ...
##  $ nox    : num  0.538 0.469 0.469 0.458 0.458 0.458 0.524 0.524 0.524 0.524 ...
##  $ rm     : num  6.58 6.42 7.18 7 7.15 ...
##  $ age    : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ dis    : num  4.09 4.97 4.97 6.06 6.06 ...
##  $ rad    : int  1 2 2 3 3 3 5 5 5 5 ...
##  $ tax    : num  296 242 242 222 222 222 311 311 311 311 ...
##  $ ptratio: num  15.3 17.8 17.8 18.7 18.7 18.7 15.2 15.2 15.2 15.2 ...
##  $ black  : num  397 397 393 395 397 ...
##  $ lstat  : num  4.98 9.14 4.03 2.94 5.33 ...
##  $ medv   : num  24 21.6 34.7 33.4 36.2 28.7 22.9 27.1 16.5 18.9 ...

Boston dataset is about housing values in suburbs of Boston. It includes 14 features defining variables that might or might not be relevant for the median value of the houses in that area. The features are:

Lets grpahically look at the data and summarize the data

library(ggplot2)
library(GGally)
#lets cast the integers to factors
data$chas = as.factor(data$chas)
ggpairs(data = data, aes(colour = chas, alpha = 0.4))
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
## `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

There are some interesting findings in the graphical overview. Firstly the distribution between chas variable is really unbalanced, which is expected as there can only be so many houses near the river and more further away. Some nonlinear clear relationships are present for example between medv-lstat and nox-dis. Also number of rooms have the anticipated positive correlation with the median value of the house.

Lets print the summary

summary(data)
##       crim                zn             indus       chas         nox        
##  Min.   : 0.00632   Min.   :  0.00   Min.   : 0.46   0:471   Min.   :0.3850  
##  1st Qu.: 0.08205   1st Qu.:  0.00   1st Qu.: 5.19   1: 35   1st Qu.:0.4490  
##  Median : 0.25651   Median :  0.00   Median : 9.69           Median :0.5380  
##  Mean   : 3.61352   Mean   : 11.36   Mean   :11.14           Mean   :0.5547  
##  3rd Qu.: 3.67708   3rd Qu.: 12.50   3rd Qu.:18.10           3rd Qu.:0.6240  
##  Max.   :88.97620   Max.   :100.00   Max.   :27.74           Max.   :0.8710  
##        rm             age              dis              rad        
##  Min.   :3.561   Min.   :  2.90   Min.   : 1.130   Min.   : 1.000  
##  1st Qu.:5.886   1st Qu.: 45.02   1st Qu.: 2.100   1st Qu.: 4.000  
##  Median :6.208   Median : 77.50   Median : 3.207   Median : 5.000  
##  Mean   :6.285   Mean   : 68.57   Mean   : 3.795   Mean   : 9.549  
##  3rd Qu.:6.623   3rd Qu.: 94.08   3rd Qu.: 5.188   3rd Qu.:24.000  
##  Max.   :8.780   Max.   :100.00   Max.   :12.127   Max.   :24.000  
##       tax           ptratio          black            lstat      
##  Min.   :187.0   Min.   :12.60   Min.   :  0.32   Min.   : 1.73  
##  1st Qu.:279.0   1st Qu.:17.40   1st Qu.:375.38   1st Qu.: 6.95  
##  Median :330.0   Median :19.05   Median :391.44   Median :11.36  
##  Mean   :408.2   Mean   :18.46   Mean   :356.67   Mean   :12.65  
##  3rd Qu.:666.0   3rd Qu.:20.20   3rd Qu.:396.23   3rd Qu.:16.95  
##  Max.   :711.0   Max.   :22.00   Max.   :396.90   Max.   :37.97  
##       medv      
##  Min.   : 5.00  
##  1st Qu.:17.02  
##  Median :21.20  
##  Mean   :22.53  
##  3rd Qu.:25.00  
##  Max.   :50.00

Unlike the datacamp says, there is a factor variable in the data, lets not normalize that. Lets normalize the others (although I am not sure if it should be done for proportions)

sdata = scale(data[,colnames(data) != "chas"])
sdata = as.data.frame(sdata)
sdata[,"chas"] = data$chas
summary(sdata)
##       crim                 zn               indus              nox         
##  Min.   :-0.419367   Min.   :-0.48724   Min.   :-1.5563   Min.   :-1.4644  
##  1st Qu.:-0.410563   1st Qu.:-0.48724   1st Qu.:-0.8668   1st Qu.:-0.9121  
##  Median :-0.390280   Median :-0.48724   Median :-0.2109   Median :-0.1441  
##  Mean   : 0.000000   Mean   : 0.00000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.007389   3rd Qu.: 0.04872   3rd Qu.: 1.0150   3rd Qu.: 0.5981  
##  Max.   : 9.924110   Max.   : 3.80047   Max.   : 2.4202   Max.   : 2.7296  
##        rm               age               dis               rad         
##  Min.   :-3.8764   Min.   :-2.3331   Min.   :-1.2658   Min.   :-0.9819  
##  1st Qu.:-0.5681   1st Qu.:-0.8366   1st Qu.:-0.8049   1st Qu.:-0.6373  
##  Median :-0.1084   Median : 0.3171   Median :-0.2790   Median :-0.5225  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 0.4823   3rd Qu.: 0.9059   3rd Qu.: 0.6617   3rd Qu.: 1.6596  
##  Max.   : 3.5515   Max.   : 1.1164   Max.   : 3.9566   Max.   : 1.6596  
##       tax             ptratio            black             lstat        
##  Min.   :-1.3127   Min.   :-2.7047   Min.   :-3.9033   Min.   :-1.5296  
##  1st Qu.:-0.7668   1st Qu.:-0.4876   1st Qu.: 0.2049   1st Qu.:-0.7986  
##  Median :-0.4642   Median : 0.2746   Median : 0.3808   Median :-0.1811  
##  Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000   Mean   : 0.0000  
##  3rd Qu.: 1.5294   3rd Qu.: 0.8058   3rd Qu.: 0.4332   3rd Qu.: 0.6024  
##  Max.   : 1.7964   Max.   : 1.6372   Max.   : 0.4406   Max.   : 3.5453  
##       medv         chas   
##  Min.   :-1.9063   0:471  
##  1st Qu.:-0.5989   1: 35  
##  Median :-0.1449          
##  Mean   : 0.0000          
##  3rd Qu.: 0.2683          
##  Max.   : 2.9865

We can see that the means are all 0 and the sds are ones as well (below).

apply(sdata, 2, sd)
##     crim       zn    indus      nox       rm      age      dis      rad 
## 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 
##      tax  ptratio    black    lstat     medv     chas 
## 1.000000 1.000000 1.000000 1.000000 1.000000 0.253994
#also save kmeand dataset that is scaled
kdata = sdata

Lets create a categorical variable out of crime rate

bins <- quantile(sdata$crim)
crime <- cut(sdata$crim, breaks = bins, include.lowest = TRUE)
#replace the earlier crime feature with the binned one
sdata$crim = crime

Lets shuffle the data set and split it into training and testing

N_train = floor(0.8 * nrow(sdata))
train_inds = sample(nrow(sdata), N_train)
train = sdata[train_inds,]
test = sdata[-train_inds, ]

Lets fit the LDA to the data using crim (binned) as the target variable

lda.fit <- lda(crim ~ ., data = train)

# print the lda.fit object
lda.fit
## Call:
## lda(crim ~ ., data = train)
## 
## Prior probabilities of groups:
## [-0.419,-0.411]  (-0.411,-0.39] (-0.39,0.00739]  (0.00739,9.92] 
##       0.2252475       0.2648515       0.2648515       0.2450495 
## 
## Group means:
##                          zn      indus        nox         rm        age
## [-0.419,-0.411]  1.05657231 -0.9494543 -0.9129891  0.4890862 -0.9234719
## (-0.411,-0.39]  -0.09112758 -0.3149961 -0.5662168 -0.1278515 -0.3392559
## (-0.39,0.00739] -0.37343545  0.2088183  0.4528324  0.1450667  0.4131525
## (0.00739,9.92]  -0.48724019  1.0149946  1.0707206 -0.3989529  0.8198422
##                        dis        rad        tax     ptratio       black
## [-0.419,-0.411]  0.8901918 -0.6979096 -0.7242401 -0.52359543  0.37834454
## (-0.411,-0.39]   0.3703638 -0.5439511 -0.5090188 -0.07141012  0.32298022
## (-0.39,0.00739] -0.4087283 -0.4054910 -0.3004067 -0.39215377  0.06795467
## (0.00739,9.92]  -0.8436446  1.6596029  1.5294129  0.80577843 -0.70487100
##                         lstat       medv      chas1
## [-0.419,-0.411] -0.7828564240  0.5651739 0.05494505
## (-0.411,-0.39]  -0.1321144022  0.0184838 0.05607477
## (-0.39,0.00739] -0.0005467482  0.2121652 0.14018692
## (0.00739,9.92]   0.8491037930 -0.7010857 0.06060606
## 
## Coefficients of linear discriminants:
##                 LD1         LD2         LD3
## zn       0.09186216  0.76403742 -0.97364847
## indus    0.02182114 -0.29512502  0.32334969
## nox      0.32436018 -0.77131468 -1.19077427
## rm      -0.10614340 -0.07929688 -0.23458667
## age      0.26648513 -0.27346979 -0.06053408
## dis     -0.08401937 -0.28870325  0.27421407
## rad      3.43391618  0.76626659  0.21795572
## tax     -0.01195246  0.15996103  0.10138861
## ptratio  0.16108892  0.03533344 -0.19138081
## black   -0.14882244  0.01539896  0.10764729
## lstat    0.17467675 -0.19285273  0.31517401
## medv     0.17514497 -0.40297127 -0.10696272
## chas1   -0.29145052 -0.11728069 -0.19164187
## 
## Proportion of trace:
##    LD1    LD2    LD3 
## 0.9487 0.0389 0.0123
# the function for lda biplot arrows
lda.arrows <- function(x, myscale = 1, arrow_heads = 0.1, color = "red", tex = 0.75, choices = c(1,2)){
  heads <- coef(x)
  arrows(x0 = 0, y0 = 0, 
         x1 = myscale * heads[,choices[1]], 
         y1 = myscale * heads[,choices[2]], col=color, length = arrow_heads)
  text(myscale * heads[,choices], labels = row.names(heads), 
       cex = tex, col=color, pos=3)
}

# target classes as numeric
classes <- as.numeric(train$crime)

# plot the lda results
plot(lda.fit, dimen = 2)
lda.arrows(lda.fit, myscale = 1)

Lets then save the crime categories for the test set and remove them from test set to avoid information leakage.

test_resp = test$crim
test$crim = NULL

And then predict the values for the test set and plot the confusion matrix

test_preds = predict(lda.fit, newdata = test)
table(correct = test_resp, preds = test_preds$class)
##                  preds
## correct           [-0.419,-0.411] (-0.411,-0.39] (-0.39,0.00739] (0.00739,9.92]
##   [-0.419,-0.411]              15             20               1              0
##   (-0.411,-0.39]                3             13               3              0
##   (-0.39,0.00739]               0             10               8              1
##   (0.00739,9.92]                0              0               1             27

The corss tabulation shows good pattern of highest values on the diagonal (meaning correct class) and least amount far away in the quantiles. In the middle classes there are some confusion with the nearby classes, which is better than misclassifying them “hardly”. Notice, however, that not every classification task possess this quantity of the classes being “close” to one another.

Lets then move on to the clustering part of the analysis, we use kdata as it is already a scaled data set and it was saved earlier. Lets begin by calculating the distances

summary(dist(kdata))
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.1343  3.2663  4.6116  4.7275  5.9572 13.8843
summary(dist(kdata, method = "manhattan"))
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##  0.2662  8.1777 12.2363 13.1698 17.1841 45.9247

Now we can cluster the data and plot the pairs with clusters as the colors. Lets define a function so it is easy to experiment with different number of clusters (and start by clustering to 4)

fit_and_plot_cluster = function(n_clusters){
  colors = c("red", "blue", "purple", "black", "orange")#max number of clusters is 5
  kfit = kmeans(kdata, centers = n_clusters)
  color_vec = kfit$cluster
  for(ii in 1:n_clusters){
    color_vec[color_vec == ii] = colors[ii]
  }
  pairs(kdata, col = color_vec)
  return(kfit)
}
fit_and_plot_cluster(4)

## K-means clustering with 4 clusters of sizes 116, 132, 192, 66
## 
## Cluster means:
##         crim         zn      indus        nox         rm        age        dis
## 1 -0.3250616 -0.4779994  0.5570912  0.4489256 -0.5659455  0.6758133 -0.5266049
## 2  1.0632703 -0.4872402  1.0149946  1.0159127 -0.3735788  0.7542188 -0.8233749
## 3 -0.3924529 -0.1456747 -0.6413903 -0.5648355  0.3732340 -0.4200290  0.3304400
## 4 -0.4135392  2.2383814 -1.1432564 -1.1776883  0.6560780 -1.4743281  1.6110176
##          rad        tax     ptratio       black      lstat       medv
## 1 -0.5898083 -0.2246773  0.07150814  0.05521256  0.5572129 -0.4686685
## 2  1.6596029  1.5294129  0.80577843 -0.75124560  0.8328654 -0.6664074
## 3 -0.5583740 -0.7292080 -0.32613034  0.36377354 -0.5816918  0.4887754
## 4 -0.6582123 -0.5426061 -0.78849501  0.34720064 -0.9528805  0.7346429
##         chas
## 1 0.10344828
## 2 0.06060606
## 3 0.06770833
## 4 0.03030303
## 
## Clustering vector:
##   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20 
##   3   3   3   3   3   3   3   3   1   3   1   3   3   3   1   3   3   1   3   1 
##  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40 
##   1   1   1   1   1   1   1   1   1   3   1   1   1   1   1   3   3   3   3   4 
##  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60 
##   4   3   3   3   3   3   3   3   1   3   3   3   3   3   4   4   4   4   3   3 
##  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80 
##   3   3   3   3   3   4   4   3   3   3   3   3   3   3   3   3   3   3   3   3 
##  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 
##   3   3   1   1   1   1   1   1   1   1   3   3   1   1   1   1   1   1   1   1 
## 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   3   1   1 
## 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 
##   1   3   3   3   1   1   3   1   1   1   1   1   1   3   3   3   3   3   3   3 
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 
##   3   3   3   3   3   3   3   4   4   4   4   4   4   4   4   4   4   4   4   4 
## 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 
##   4   4   4   4   4   3   3   1   3   1   1   1   3   3   1   3   1   3   1   1 
## 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 
##   3   1   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   4   3 
## 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 
##   3   3   3   4   3   3   3   3   3   4   4   4   4   4   4   4   4   3   3   3 
## 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   4   3   3 
## 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 
##   3   3   3   4   4   4   4   4   4   4   4   4   4   3   3   3   3   3   4   4 
## 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 
##   4   3   4   4   3   3   3   3   3   1   1   3   1   3   3   1   1   1   3   3 
## 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 
##   3   3   3   3   3   3   3   3   3   3   3   4   4   3   3   3   3   3   3   3 
## 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 
##   3   4   3   4   4   3   3   4   4   4   4   4   4   4   4   4   2   2   2   2 
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 
##   2   2   2   2   2   2   2   2   1   1   1   1   1   1   1   1   1   1   1   1 
## 501 502 503 504 505 506 
##   1   1   1   3   1   1 
## 
## Within cluster sum of squares by cluster:
## [1]  673.4331 1089.3818  962.4021  294.9259
##  (between_SS / total_SS =  54.2 %)
## 
## Available components:
## 
## [1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss"
## [6] "betweenss"    "size"         "iter"         "ifault"

Cluster separation seems to be decent, so that in every plot the different colors somewhat focus on different regions of the plot. However there are still some overlaps, so lets try to find the optimal number of clusters

set.seed(42)
k_max = 15
twcss <- sapply(1:k_max, function(k){kmeans(kdata, k)$tot.withinss})
qplot(x = 1:k_max, y = twcss, geom = 'line')

So it seems that the most radical drop is at 5 clusters, so lets go with that

fit_and_plot_cluster(5)

## K-means clustering with 5 clusters of sizes 130, 107, 154, 65, 50
## 
## Cluster means:
##         crim         zn      indus        nox         rm        age        dis
## 1  1.0751732 -0.4872402  1.0149946  1.0214115 -0.3916946  0.7502046 -0.8176637
## 2 -0.3231486 -0.4822312  0.6308150  0.5041272 -0.5223445  0.7753457 -0.5711540
## 3 -0.3976664 -0.1658009 -0.5908351 -0.6609769 -0.1605287 -0.6491081  0.5401341
## 4 -0.4140702  2.2813035 -1.1562550 -1.1768217  0.7293996 -1.4086475  1.5645584
## 5 -0.3408088 -0.1562287 -0.6660268 -0.1688251  1.6824321  0.2207229 -0.3493438
##          rad        tax    ptratio       black      lstat        medv
## 1  1.6596029  1.5294129  0.8057784 -0.76735584  0.8657319 -0.72260607
## 2 -0.5943978 -0.1915536  0.0874508  0.03673407  0.5492158 -0.48624639
## 3 -0.5739417 -0.6919945 -0.0640434  0.36078750 -0.3846437  0.01486057
## 4 -0.6656011 -0.5702843 -0.8094692  0.35416061 -0.9741045  0.81491803
## 5 -0.4099346 -0.6938362 -1.0326050  0.34487995 -0.9751860  1.81417906
##         chas
## 1 0.04615385
## 2 0.10280374
## 3 0.03896104
## 4 0.06153846
## 5 0.16000000
## 
## Clustering vector:
##   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20 
##   3   3   5   3   5   3   3   3   2   3   3   3   3   3   3   3   3   2   3   3 
##  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40 
##   2   2   2   2   2   2   2   2   2   3   2   2   2   2   2   3   3   3   3   4 
##  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60 
##   4   3   3   3   3   3   3   3   2   3   3   3   3   3   4   4   4   4   3   3 
##  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80 
##   3   3   3   3   4   4   4   3   3   3   3   3   3   3   3   3   3   3   3   3 
##  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 
##   3   3   3   3   3   3   3   3   3   5   3   3   3   3   3   3   3   5   5   5 
## 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 
##   3   3   2   2   2   2   2   2   2   2   3   2   2   2   2   2   2   2   2   2 
## 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2 
## 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 
##   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   2   5   2   2 
## 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 
##   2   5   5   5   2   2   5   2   2   2   2   2   3   3   3   3   3   3   5   5 
## 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 
##   5   3   5   5   3   3   5   4   4   4   4   4   4   4   4   4   4   4   4   4 
## 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 
##   4   4   4   4   4   3   3   3   3   2   2   2   3   3   3   3   3   5   2   2 
## 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 
##   5   2   5   5   5   5   5   5   5   3   3   5   5   5   3   3   3   5   4   3 
## 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 
##   3   3   3   4   3   3   3   3   3   3   3   3   4   4   4   4   4   5   5   5 
## 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 
##   5   5   5   5   5   3   5   5   5   3   3   3   3   5   4   4   4   4   3   5 
## 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 
##   5   5   5   4   4   4   4   4   4   4   4   4   4   3   3   3   3   3   4   4 
## 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 
##   4   3   4   4   5   3   5   3   3   3   3   3   2   3   3   2   2   2   3   3 
## 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 
##   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3   3 
## 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 
##   3   4   3   4   4   3   3   4   4   4   4   4   4   4   4   4   1   1   1   1 
## 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 
##   1   1   1   1   1   1   1   1   1   5   5   1   1   1   1   1   1   1   1   1 
## 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 
##   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1   1 
## 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 
##   1   1   1   1   1   1   1   1   2   2   2   2   2   2   3   3   2   2   2   2 
## 501 502 503 504 505 506 
##   2   2   2   2   2   2 
## 
## Within cluster sum of squares by cluster:
## [1] 1044.1446  620.4854  463.8670  288.6658  255.5570
##  (between_SS / total_SS =  59.5 %)
## 
## Available components:
## 
## [1] "cluster"      "centers"      "totss"        "withinss"     "tot.withinss"
## [6] "betweenss"    "size"         "iter"         "ifault"

Some of the variables are very well separated in the clusters, i.e., nox vs age/dis/rad, where e.g. the purple cluster is such that the nox, rad and age are high and dis is low. Similar differences can be recognized in other clusters as well.


(more chapters to be added similarly as we proceed with the course!)